package com.tanhua.dubbo.utils;

import com.tanhua.model.mongo.Friend;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.MovementTimeLine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class TimeLineService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Async("tanhuaPool")
    public void saveTimeLine(Movement movement) {
        String name = Thread.currentThread().getName();
        System.out.println("保存时间线数据的线程："+name);
//        try {
//            //模拟保存数据较慢
//            Thread.sleep(5000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        //2、查询当前用户的所有好友
        Long userId = movement.getUserId(); //动态发布人
        Criteria criteria = Criteria.where("userId").is(userId);
        Query query = Query.query(criteria);
        List<Friend> friends = mongoTemplate.find(query, Friend.class);
        //3、排除不可见的用户(忽略)，记录关系表数据
        //如果当前用户有10000W个好友，保存关系时保存10000次
        //比如保存一条 10毫秒
        //发布一条动态  10 * 10000 = 100秒
        for (Friend friend : friends) {
            MovementTimeLine line = new MovementTimeLine();
            line.setUserId(userId);
            line.setMovementId(movement.getId());
            line.setFriendId(friend.getFriendId());
            line.setCreated(System.currentTimeMillis());
            mongoTemplate.save(line);
        }
    }
}
